﻿
function initChat(username, orgId) {
    var chat = $.connection.chatHub;
    registerClientMethods(chat);
    $.connection.hub.start().done(function () {
        chat.server.online(username, orgId);
        $('#dg').datagrid({
            onDblClickRow: function (rowIndex, rowData) {
                createPrivateDialog(rowData.Id, rowData.Name, chat);
            }
        });

        $('#ttOrg').tree({
            onSelect: function (node) {
                var orgId = node.id;
                chat.server.getUsersByOrg(orgId).done(function (data) {
                    $('#dg').datagrid('loadData', data);
                });

            }
        });
    });
}

function registerClientMethods(chatHub) {
    // 用户连接后
    chatHub.client.onConnected = function (id, userName, allUsers) {
        $('#dg').datagrid('loadData', allUsers);
    }
    //有新用户连接
    chatHub.client.onNewUserConnected = function (user) {
        var selectedNode = $('#ttOrg').tree('getSelected');
        if (selectedNode && user.OrgId == selectedNode.id) {
            $('#dg').datagrid('appendRow', user);
        }
    }
    //用户断开连接
    chatHub.client.onUserDisconnected = function (id) {
        var rowIndex = $('#dg').datagrid('getRowIndex', id);
        $('#dg').datagrid('deleteRow', rowIndex);
    }
    //发送私人消息
    chatHub.client.sendPrivateMessage = function (fromId, userName, message) {
        createPrivateDialog(fromId, userName, chatHub);
        $('#' + fromId).find('#divMessage').append('<div class="message"><span class="userName">' + userName + '</span>: ' + message + '</div>');
        var height = $('#' + fromId).find('#divMessage')[0].scrollHeight;
        $('#' + fromId).find('#divMessage').scrollTop(height);
    }
}

//创建私人聊天窗口
function createPrivateDialog(id, title, chatHub) {
    var _dialog = $('#' + id);
    if (_dialog.length == 0) {
        var content = '<div>' +
            '<div id="divMessage" style="height: 90px; border-bottom: 1px solid;overflow:auto">' +
            '</div>' +
            '<div class="buttonBar">' +
            '<input id="txtPrivateMessage" class="msgText" type="text" />' +
            '<input id="btnSendMessage" type="button" value="发送" />' +
            '</div>' +
            '</div>';
        var _dialogOpts = {
            closed: true,
            title: title,
            width: 300,
            height: 160,
            onClose: function () {
                _dialog.dialog('destroy');
            }
        }
        var _dialog = $(content).attr('id', id).dialog(_dialogOpts);
        _dialog.find('#btnSendMessage').click(function () {
            var message = _dialog.find('#txtPrivateMessage').val();
            chatHub.server.sendPrivateMessage(id, message);
        });
    }
    _dialog.dialog('open');
}